import redis.asyncio as aioredis
from typing import Optional, Any

import asyncio


class RedisAsyncClient:
    def __init__(self, url: str, max_connections: int = 10):
        self._url = url
        self._max_connections = max_connections
        self._pool = None
        self._init_lock = asyncio.Lock()

    async def init(self):
        if self._pool:
            return
        async with self._init_lock:
            if not self._pool:
                self._pool = await aioredis.from_url(
                    self._url,
                    encoding="utf-8",
                    decode_responses=True,
                    max_connections=self._max_connections,

                )

    async def close(self):
        """关闭连接池"""
        if self._pool:
            await self._pool.close()
            self._pool = None

    async def get(self, key: str) -> Any:
        """获取键的值"""
        if not self._pool:
            raise RuntimeError("Redis pool not initialized")
        return await self._pool.get(key)

    async def set(self, key: str, value: Any, expire: int = None) -> None:
        """设置键值，可以带过期时间（秒）"""
        if not self._pool:
            raise RuntimeError("Redis pool not initialized")
        await self._pool.set(key, value, ex=expire)

    async def delete(self, key: str) -> None:
        """删除键"""
        if not self._pool:
            raise RuntimeError("Redis pool not initialized")
        await self._pool.delete(key)

    async def exists(self, key: str) -> bool:
        """判断键是否存在"""
        if not self._pool:
            raise RuntimeError("Redis pool not initialized")
        return await self._pool.exists(key) > 0

    # 你可以继续添加通用方法，如 hget, hset, sadd, smembers 等

# 用法示例（FastAPI 生命周期钩子集成）：
#
# from fastapi import FastAPI
# from redis_async_client import RedisAsyncClient
#
# app = FastAPI()
# redis_client = RedisAsyncClient("redis://localhost:6379/0")
#
# @app.on_event("startup")
# async def startup_event():
#     await redis_client.init()
#
# @app.on_event("shutdown")
# async def shutdown_event():
#     await redis_client.close()
#
# # 在路由中直接用 redis_client 即可

if __name__ == '__main__':
    async def main():
        redis_client = RedisAsyncClient("redis://:ruoyi123@localhost:6379/0")
        await redis_client.init()
        await redis_client.set("test", "test")
        res = await redis_client.get("test")
        print(res)
    asyncio.run(main())
